package com.lant.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync // 开启异步
public class ThreadConfig {
    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池的大小经验公式 T = C(cpu数目)/P(密集计算所占的时间比重) 核心线程数
        executor.setCorePoolSize(10);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 设置队列容量（核心线程等待队列）
        executor.setQueueCapacity(20);
        // 最大空闲时间(非核心线程能够空闲的最长时间)
        executor.setKeepAliveSeconds(3000);
        // 线程名称前缀
        executor.setThreadNamePrefix("ThreadPool");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.initialize();
        return executor;
    }
}
